//
//  ZYQiniuTool.m
//  ZYNaNian
//
//  Created by apple on 15/12/16.
//  Copyright © 2015年 ZYNaNian. All rights reserved.
//

#import "ZYQiniuTool.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>

// 判断是不是iOS8以上系列
#define iOS8 ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0)

/**
     NSError *error;
     QNFileRecorder *file = [QNFileRecorder fileRecorderWithFolder:@"保存目录" error:&error];
     //check error
     QNUploadManager *upManager = [[QNUploadManager alloc] initWithRecorder:file];
 */
static QNUploadManager *_manager; // 请求管理者
@implementation ZYQiniuTool

// 如果希望获取上传进度和中途取消上传，需要实现下面的block，并作为参数传入option
/**
 *    上传进度回调函数
 *
 *    @param key     上传时指定的存储key
 *    @param percent 进度百分比
 */
//typedef void (^QNUpProgressHandler)(NSString *key, float percent);

/**
 *    上传中途取消函数
 *
 *    @return 如果想取消，返回True, 否则返回No
 */
//typedef BOOL (^QNUpCancellationSignal)(void);

+ (void)initialize{
    if (_manager == nil) {
        
        NSError *error;
        QNFileRecorder *file = [QNFileRecorder fileRecorderWithFolder:@"保存目录" error:&error];
        NSLog(@"recorder error %@", error);
        _manager = [[QNUploadManager alloc] initWithRecorder:file];
        
//        _manager = [[QNUploadManager alloc] init];
    }
}

+ (void)putData:(NSData *)data key:(NSString *)key token:(NSString *)token complete:(void(^)(id info, NSDictionary *resp))complete option:(QNUploadOption *)option
{
    [_manager putData:data key:key token:token complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
          if (complete) {
              complete(info, resp);
          }
        
      } option:option];
    
}

+ (void)putFile:(NSString *)file key:(NSString *)key token:(NSString *)token complete:(void(^)(id info, NSDictionary *resp))complete option:(QNUploadOption *)option
{
     [_manager putFile:file key:key token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
         
         if (complete) {
             complete(info, resp);
         }
         
     } option:option];
}

+ (void)putAsset:(id)asset key:(NSString *)key token:(NSString *)token complete:(void(^)(id info, NSDictionary *resp))complete option:(QNUploadOption *)option
{
    if (![asset isKindOfClass:[ALAsset class]] && ![asset isKindOfClass:[PHAsset class]]) {
        return;
    }
    
    if (iOS8) {
        [_manager putPHAsset:asset key:key token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            if (complete) {
                complete(info, resp);
            }
        } option:option];
    } else {
        [_manager putALAsset:asset key:key token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            if (complete) {
                complete(info, resp);
            }
        } option:option];
    }
}

+ (void)putPHAsset:(PHAsset *)asset key:(NSString *)key token:(NSString *)token complete:(void(^)(id info, NSDictionary *resp))complete option:(QNUploadOption *)option
{
    [_manager putPHAsset:asset key:key token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        if (complete) {
            complete(info, resp);
        }
    } option:option];
}

+ (void)putALAsset:(ALAsset *)asset key:(NSString *)key token:(NSString *)token complete:(void(^)(id info, NSDictionary *resp))complete option:(QNUploadOption *)option
{
    [_manager putALAsset:asset key:key token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        if (complete) {
            complete(info, resp);
        }
    } option:option];
}

/**
 *  保存数据
 *
 *  @param size 数据大小
 *
 *  @return 数据路径
 */
//+ (NSURL *)saveTempfileWithData:(NSData *)data fileName:(NSString *)fileName
//{
////    NSError *error = nil;
////    
////    NSString *file = [NSString stringWithFormat:@"%@/", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
////    NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:file error:&error];
////    
////    ZYLog(@"saveTempfileWithData-----%zd",  array.count);
////    
////    NSURL *fileUrl;
////    if (array.count>2) {
////        NSString *lastFile = array.lastObject;
////        
////        NSRange range;
////        range.location = [lastFile rangeOfString:@""].location + 1;
////        range.length = [lastFile rangeOfString:@"upload_"].location - range.location;
////        fileName = nil;
////    } else {
////        NSString *name = @"upload_1.text";
////        [NSURL fileURLWithPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:name]];
//////        fileName = [NSString stringWithFormat:@"upload_1/%@", fileName];
////    } NSCachesDirectory
//    
//   
////    NSLog(@"%@",[[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:fileName]);
//    
//    
////    BOOL is = [[NSFileManager defaultManager] createFileAtPath:[[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:fileName] contents:data attributes:nil];
////    NSLog(@"%d",is);
//    
//    
//    NSURL *fileUrl = [NSURL fileURLWithPath:[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:fileName] ];
//    
//    
//    ZYLog(@"saveTempfileWithData----------%@", fileUrl);
//    NSError *error = nil;
//
//    if ([data writeToFile:fileUrl.path options:NSDataWritingAtomic error:&error]) {
//        
//        NSLog(@"%d----%@---",__LINE__,fileUrl);
//        ZYLog(@"%@", [UIImage imageWithData:[NSData dataWithContentsOfFile:fileUrl.path]]);//[UIImage imageWithContentsOfFile:fileUrl.path]);
//        
//    }else{
//        
//       NSLog(@"%d---%@",__LINE__,error);
//    }
//
////    NSString *localPath = @"Documents/muArrayFindHistory.src";
////    
////    NSString * pathMuArrayFindHistory = [NSHomeDirectory() stringByAppendingPathComponent:localPath];
////    
////    BOOL success = [NSKeyedArchiver archiveRootObject:data toFile:pathMuArrayFindHistory];
//
////    NSString *homedirectory = NSHomeDirectory();
////    [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] ;
////    NSString *fileUrl = [homedirectory stringByAppendingPathComponent:@"object.archiver"];
////    
////    NSString *homepath =[homedirectory stringByAppendingPathComponent:@"my.archiver"];//扩展名可以是任意的
//    //归档,可以对字符串、数字进行归档，当然了一可以对NSArray,NSDictionary进行归档，归档成功返回YES，失败返回NO
//    
//    
//    
////    BOOL flag = [NSKeyedArchiver archiveRootObject:@"zhangsan" toFile:homepath];
////    if(success){
////        NSLog(@"数据归档成功");
////    }else{
////        NSLog(@"数据归档失败");
////    }
////    
////    
//    return fileUrl;
//}


+ (NSString *)saveTempfileWithData:(NSData *)data fileName:(NSString *)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];   // 保存文件的名称
    
    BOOL success = [data writeToFile:filePath atomically:YES];

    if(success){
        NSLog(@"数据归档成功");
        
        return filePath;
    }else{
        NSLog(@"数据归档失败");
    }
    
    return nil;
}


/**
 *  移除数据
 *
 *  @param path 数据路径
 */
+ (void)removeTempfile:(NSURL *)fileUrl
{
    NSError *error = nil;
//    [[NSFileManager defaultManager] removeItemAtPath:file error:&error];
    [[NSFileManager defaultManager] removeItemAtURL:fileUrl error:&error];
}

@end